Skip to content

Largest subarray with 0 sum ​

Largest subarray with 0 sum — GeeksforGeeks

Given an array of positive and negative integers, find the length of the longest contiguous subarray whose elements sum to 0.

Approach ​

Do prefix sums. When two prefix sums are equal, then the sum between is 0. So, use a hashmap to store the minimum index of each prefix sum, and do a subtract. To make it easier, push arr[0] = 0; map[0] = 0. And then rest of the prefix sums, just continue as normal.

Remarks ​

I couldn't get the arr[0] = 0; map[0] = 0 part. Pasted image 20260722235146.png